package com.yycx.module.bus.provider.handler.haiying.custombalance;

import com.yycx.common.base.entity.EntityMap;
import com.yycx.common.base.utils.FlymeUtils;
import com.yycx.common.constants.CommonConstants;
import com.yycx.common.mybatis.interceptor.PageInterceptor;
import com.yycx.common.mybatis.model.PageParams;
import com.yycx.common.mybatis.query.CriteriaQuery;
import com.yycx.common.security.OpenHelper;
import com.yycx.module.admin.client.entity.BaseUser;
import com.yycx.module.bus.client.entity.BusCustom;
import com.yycx.module.bus.client.entity.BusPayment;
import com.yycx.module.bus.client.entity.BusSaleman;
import com.yycx.module.bus.client.enums.AmountTypeEnum;
import com.yycx.module.bus.provider.service.BusCustomService;
import com.yycx.module.bus.provider.service.BusPaymentService;
import com.yycx.module.bus.provider.service.BusSalemanService;
import com.yycx.module.bus.provider.service.hy.BusPaymentOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;

/**
 * 资保金收款收款单选择列表
 *
 * @author zyf
 */
@Component
public class HyBondSelectListHandler implements PageInterceptor<BusPayment> {


    @Autowired
    private BusSalemanService salemanService;


    @Autowired
    private BusPaymentOrderService paymentOrderService;

    @Autowired
    private BusPaymentService paymentService;

    @Override
    public void prepare(CriteriaQuery<BusPayment> cq, PageParams pageParams, EntityMap params) {
        Long saleManId = params.getLong("saleManId");
        Long companyId = OpenHelper.getCompanyId();
        BusSaleman saleMan = salemanService.getById(saleManId);

        if (FlymeUtils.isEmpty(saleMan)) {
            saleMan = new BusSaleman();
        }
        cq.select(BusPayment.class, "*");
        cq.addSelect(BusSaleman.class, "saleManName");
        //没使用
        cq.gt("surplusAmount", 0);
        cq.eq(true, "amountType", AmountTypeEnum.CustomBond);
        cq.eq(true, "payment.companyId", companyId);
        cq.eq(FlymeUtils.isNotEmpty(saleManId), "payment.saleManId", saleMan.getSaleManId());
        cq.eq(true, "payment.paymentState", CommonConstants.INT_2);
        cq.createJoin(BusSaleman.class);
        cq.orderByDesc("payment.createTime");
    }
    @Override
    public List<EntityMap> complete(CriteriaQuery<BusPayment> cq, List<EntityMap> result, EntityMap extra) {
        for (EntityMap entityMap : result) {
            Long paymentId = entityMap.get("paymentId");
            BigDecimal amount = entityMap.getBigDecimal("amount");
            BigDecimal useAmount = paymentOrderService.totalByPaymentId(paymentId);
            BigDecimal surplusAmount = amount.subtract(useAmount);
            entityMap.put("surplusAmount", surplusAmount);
            paymentService.updateSurplusAmount(paymentId, surplusAmount);
        }
        return result;
    }

}
